﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using DHQGHN.PM2.Models;

namespace DHQGHN.PM2.Controllers
{
    public class HomeController : BaseController
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HomeController));
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        public ActionResult Manage()
        {
            try
            {
                HttpCookie cook = new HttpCookie("testcook");
                cook = Request.Cookies["checkpopup"];
                ViewBag.Cok = cook.Value;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }

            return View();

        #region Temp
		 
        //    ReportModel rp = new ReportModel();
        //    string strAdminCode = MyUser.AdminCode; //"1008202749";
        //    string strCommuneCode = String.Empty;
        //    if (strAdminCode.Count() == 10)
        //    {
        //        strCommuneCode = strAdminCode.Substring(5, 5);
        //    }
        //    else if (strAdminCode.Count() == 5)
        //    {
        //        strCommuneCode = strAdminCode.Substring(2, 3);
        //    }
        //    else
        //    {
        //        strCommuneCode = strAdminCode;
        //    }
        //    try
        //    {
        //        using (WebClient wc = new WebClient())
        //        {
        //            if (ModelState.IsValid)
        //            {
        //                Helper.SetHeaderInfo(wc, "Getreportall");
        //                wc.Encoding = Encoding.UTF8;
        //                wc.Headers["Content-type"] = "application/json; charset=utf-8";
        //                string UrlPath = string.Format("{0}{1}", serviceUrl, "OnlineService.svc/Getreportall");

        //                string result = wc.DownloadString(UrlPath);
        //                rp = JsonConvert.DeserializeObjectAsync<ReportModel>(result).Result;
        //            }
        //            else
        //            {
        //                ModelState.Values.SelectMany(v => v.Errors);
        //            }

        //        }
        //        ViewBag.ServiceUrl = serviceUrl;
        //        ViewBag.CommuneCode = strCommuneCode;
        //        ViewBag.FileNames = GetFileFromDirectory("Content/files/", "*.pdf");
        //        ViewBag.FileToViews = GetFileToView("Content/files/", "*.pdf");
        //        ViewBag.DocumentLinkCaption = GetDocumentLinkCaption();
        //        ViewBag.VideoUrl = GetVideoUrl();
        //        ViewBag.VideoLinkCaption = GetVideoLinkCaption();

        //        ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
        //        ViewBag.ActiveMenus[0] = "active";
        //        ViewBag.Message = "Quan ly tong dieu tra";

        //        PreparingGeneralData();

        //    }
        //    catch (Exception ex)
        //    {
        //        logger.Error(ex.ToString());
        //        throw;
        //    }

        //    return View(rp); 
	#endregion
        }

        public ActionResult LapBangKe()
        {
            ViewBag.Message = "Lap bang ke";

            return View();
        }

        #region bieu do so sanh cac phuong thuc dieu tra (vanduong-23/07/2015)

        //private void PreparingGeneralData()
        //{
        //    try
        //    {
        //        SurveyMethodInfoModel data = GetGeneralData();
        //        ViewBag.GeneralData = data;
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.Error(ex.ToString());
        //        throw;
        //    }
        //}

        //private SurveyMethodInfoModel GetGeneralData()
        //{
        //    try
        //    {
        //        using (WebClient wc = new WebClient())
        //        {
        //            Helper.SetHeaderInfo(wc, "GetSurveyMethodCount");
        //            wc.Encoding = Encoding.UTF8;
        //            wc.Headers["Content-type"] = "application/json; charset=utf-8";
        //            string jsonResult = wc.DownloadString(serviceUrl + "StatisticsService.svc" + "/" + "GetSurveyMethodCount");

        //            SurveyMethodInfoModel result =
        //                JsonConvert.DeserializeObjectAsync<SurveyMethodInfoModel>(jsonResult).Result;


        //            return result;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.Error(ex.ToString());
        //        throw;
        //    }
        //}

        #endregion

        #region Download file -vanduong(28/07/2015)

        private List<string> GetFileFromDirectory(string direc, string fileType)
        {
            try
            {
                string path = Server.MapPath("~/" + direc);
                System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(path);
                System.IO.FileInfo[] fileInfo = dirInfo.GetFiles(fileType);
                List<string> lst = new List<string>(fileInfo.Length);
                foreach (var item in fileInfo)
                {
                    lst.Add(item.Name);
                }

                return lst;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        [HttpGet]
        public ActionResult DowloadFile(string fileName)
        {
            if (System.IO.Path.GetExtension(fileName) == ".pdf")
            {
                string fullPath = System.IO.Path.Combine(Server.MapPath("~/Content/files/"), fileName);

                return File(fullPath, "application/pdf", fileName);
            }
            else
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden);
            }

        }

        [HttpGet]
        public FileResult PDFDisplay(string fileName)
        {
            if (System.IO.Path.GetExtension(fileName) == ".pdf")
            {
                string filepath = Server.MapPath("~/Content/files/" + fileName);
                byte[] pdfByte = Helper.GetBytesFromFile(filepath);
                return File(pdfByte, "application/pdf");
            }

            return null;
        }

        #endregion

        private List<string> GetVideoUrl()
        {
            string video1 = ConfigurationManager.AppSettings["Video1"];
            string video2 = ConfigurationManager.AppSettings["Video2"];

            return new List<string>(){
                video1,
                video2
            };
        }

        private List<string> GetVideoLinkCaption()
        {
            return new List<string>() { 
                "Video hướng dẫn sử dụng Quản lý tổng điều tra",
                "Video hướng dẫn sử dụng thu nhận Online"
            };
        }

        public ActionResult WatchVideo(string url, string title)
        {
            if (UrlIsValid(url))
            {
                ViewBag.Url = url;
                ViewBag.Title = title;

                return View();    
            }
            
            return Redirect("~/Home/Manage");
        }

        private bool UrlIsValid(string url)
        {
            List<string> urlVideo = GetVideoUrl();
            if(urlVideo.Contains(url))
            {
                return true;
            }

            return false;
        }

        private List<string> GetFileToView(string direct, string fileType)
        {
            try
            {
                List<string> fileNames = GetFileFromDirectory(direct, fileType);

                return fileNames;
                List<string> items = new List<string>();
                for (int i = 0; i < fileNames.Count; i++)
                {
                    items.Add(System.IO.Path.Combine(direct, fileNames[i]));
                }

                return items;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private List<string> GetDocumentLinkCaption()
        {
            return new List<string>(){
                "Hướng dẫn sử dụng Quản lý tổng điều tra",
                "Hướng dẫn sử dụng thu nhận Online"
            };
        }
    }
}